﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using viBlog.Classes;
using viBlog.Controllers;
using visinia.SmartEngine;

public partial class Admin_Pages_viBlog_Posts_PostEditor : BaseAdminPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebPageController.AddScriptLink(Page, WebRoots.GetAdminPagesRoot + "viBlog/Posts/Editor.js");
        WebPageController.AddCssLink(Page, WebRoots.GetAdminPagesRoot + "viBlog/Posts/EditorStyle.css");        
       // if (!IsPostBack)
        {
            AUTHORS.DataSource = Membership.GetAllUsers();
            AUTHORS.DataBind();

            List<Category> Categories = CategoryController.GetCategories();
            foreach (Category category in Categories)
            {
                HtmlAnchor a = new HtmlAnchor();
                a.InnerText = category.Name;
                CategoriesList.Controls.Add(a);
            }

            List<Tag> tags = TagController.GetTags();
            foreach (Tag tag in tags)
            {
                HtmlAnchor a = new HtmlAnchor();
                a.InnerText = tag.Name;
                TagsList.Controls.Add(a);
            }            
            //create a new post
            if (Request.QueryString["PostId"] == null)
            {
                DATE.Text = DateTime.Now.ToString();
                POST_STATUS.Text = Translate("viblog", "NewPost"); 
            }
            else
            {// edit an already existing post
                int PostId = Convert.ToInt32(Request.QueryString["PostId"]);
                Post post = PostController.GetPostAdmin(PostId);
                TITLE.Text = post.Title;
                DATE.Text = post.Date.ToString();                
                URL.Visible = true;
                URL.Value = post.Url;                
                SUMMARY.Text = post.Summary;
                DESCRIPTION.Text = PostController.GetPostDescriptionAdmin(PostId);
                ALLOW_COMMENTS.Checked = post.AllowComments;
                POST_STATUS.Text = post.IsDraft ? Translate("viblog", "Draft") : Translate("viblog", "Published");                
                if (Request.QueryString["saved"] == "true")
                {                    
                    if (post.IsDraft)
                    {
                        MESSAGE.Text = Translate("viblog", "DraftSaved");
                        PreviewLink.Visible = false;
                    }
                    else
                    {
                        MESSAGE.Text = Translate("viblog", "PostSaved");
                        PreviewLink.NavigateUrl = post.Url;
                    }
                    MessageLocal.Visible = true;
                }
                //categories
                List<Category> postCategories = CategoryController.GetCategories(post.PostId);
                if (postCategories != null)
                {
                    foreach (Category category in postCategories)
                    {
                        SelectedCategories.Value += category.Name + ',';
                    }
                }
                //tags
                List<Tag> postTags = TagController.GetTags(post.PostId);
                if (postTags != null)
                {
                    foreach (Tag tag in postTags)
                    {
                        SelectedTags.Value += tag.Name + ',';
                    }
                }
            }
        }
    }

    protected void PUBLISH_Click(object sender, EventArgs e)
    {
        Save(false);
    }

    protected void DRAFT_Click(object sender, EventArgs e)
    {
        Save(true);
    }

    protected void Save(bool isDraft)
    {
        //save a new post
        if (Request.QueryString["PostId"] == null)
        {
            Post post = new Post();
            post.Title = TITLE.Text;
            post.Author = AUTHORS.SelectedValue;
            post.Date = Convert.ToDateTime(DATE.Text);
            post.Url = RemoveIllegalCharacters(post.Title);
            post.Summary = SUMMARY.Text;
            post.AllowComments = ALLOW_COMMENTS.Checked;                   
            post.IsDraft = isDraft;                     
            int postid = PostController.AddPost(post, DESCRIPTION.Text);            
            //categories            
            string[] selectedCategories = SelectedCategories.Value.Split(',');
            foreach (string categoryName in selectedCategories)
            {
                if (string.IsNullOrEmpty(categoryName.Trim()))
                    continue;
                Category existingCategory = CategoryController.GetCategory(categoryName);
                if (existingCategory != null)
                {
                    CategoryController.InsertCategory(existingCategory.CategoryId, postid);
                }
                else
                {
                    int id = CategoryController.AddCategory(new Category(categoryName));
                    CategoryController.InsertCategory(id, postid);
                }
            }

            //tags
            TagController.ResetTags(postid);
            string[] selectedtags = SelectedTags.Value.Split(',');
            foreach (string tagName in selectedtags)
            {
                if (string.IsNullOrEmpty(tagName.Trim()))
                    continue;
                Tag existingTag = TagController.GetTag(tagName);
                if (existingTag != null)
                {
                    TagController.InsertTag(existingTag.TagId, postid);
                }
                else
                {
                    int id = TagController.AddTag(new Tag(tagName));
                    TagController.InsertTag(id, postid);
                }
            }
            // reload the newly created post
            Response.Redirect(SystemMenu.CallPage("viBlog", "EditPost", "PostId", postid.ToString()) + "&saved=true");
        }
        else
        {// update an already existing post
            int postid = 0;
            if (!Int32.TryParse(Request.QueryString["PostId"], out postid))
                return;
            Post post = PostController.GetPostAdmin(postid);
            if (post == null)
                return;
            post.Title = TITLE.Text;
            post.Author = AUTHORS.SelectedValue;
            post.Date = Convert.ToDateTime(DATE.Text);
            post.Url = RemoveIllegalCharacters(post.Title);
            post.Summary = SUMMARY.Text;
            post.AllowComments = ALLOW_COMMENTS.Checked;                      
            post.IsDraft = isDraft;
            PostController.UpdatePost(post, DESCRIPTION.Text);

            //categories
            CategoryController.ResetCategories(post.PostId);            
            string[] selectedCategories = SelectedCategories.Value.Split(',');
            foreach (string categoryName in selectedCategories)
            {
                if (string.IsNullOrEmpty(categoryName.Trim()))
                    continue;
                Category existingCategory = CategoryController.GetCategory(categoryName);
                if (existingCategory != null)
                {
                    if (!CategoryController.GetCategories(post.PostId).Exists(p => p.CategoryId == existingCategory.CategoryId))
                        CategoryController.InsertCategory(existingCategory.CategoryId, post.PostId);
                }
                else
                {
                    int id = CategoryController.AddCategory(new Category(categoryName));
                    CategoryController.InsertCategory(id, post.PostId);
                }
            }
                        
            //tags
            TagController.ResetTags(post.PostId);
            string[] selectedtags = SelectedTags.Value.Split(',');
            foreach (string tagName in selectedtags)
            {
                if (string.IsNullOrEmpty(tagName.Trim()))
                    continue;
                Tag existingTag = TagController.GetTag(tagName);
                if (existingTag != null)
                {
                    if (!TagController.GetTags(post.PostId).Exists(p => p.TagId == existingTag.TagId))
                        TagController.InsertTag(existingTag.TagId, post.PostId);
                }
                else
                {
                    int id = TagController.AddTag(new Tag(tagName));
                    TagController.InsertTag(id, post.PostId);
                }
            }
            Response.Redirect(SystemMenu.CallPage("viBlog", "EditPost", "PostId", postid.ToString()) + "&saved=true");
        }
    }

    bool Exist(string[] values, string find)
    {
        foreach (string value in values)
        {
            if (value.Trim().CompareTo(find) == 0)
                return true;
        }
        return false;
    }

    protected void CANCEL_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["PostId"] == null)
            Response.Redirect(Request.RawUrl);
        Response.Redirect(SystemMenu.CallPage("viBlog", "EditPost", "PostId", Request.QueryString["PostId"])); 
    }
    
    private static string RemoveIllegalCharacters(string Title)
    {
        if (string.IsNullOrEmpty(Title))
            return Title;

        Title = Title.Replace(":", string.Empty);
        Title = Title.Replace("/", string.Empty);
        Title = Title.Replace("?", string.Empty);
        Title = Title.Replace("#", string.Empty);
        Title = Title.Replace("[", string.Empty);
        Title = Title.Replace("]", string.Empty);
        Title = Title.Replace("@", string.Empty);
        Title = Title.Replace("*", string.Empty);
        Title = Title.Replace(".", string.Empty);
        Title = Title.Replace(",", string.Empty);
        Title = Title.Replace("\"", string.Empty);
        Title = Title.Replace("&", string.Empty);
        Title = Title.Replace("'", string.Empty);
        Title = Title.Replace(" ", "-");
        return HttpUtility.UrlEncode(Title).Replace("%", string.Empty);
    }
}
